var express = require('express');
var router = express.Router();
var Post = require('../models/Post');
Comment = require('../models/comment');
//加密模块
var crypto = require('crypto');
var User = require('../models/user');
var multer = require('multer');
var storage = multer.diskStorage({
  destination:function (req, file, cb) {
    cb(null,'./public/images')
  },
  filename:function (req, file, cb) {
    cb(null,file.originalname)
  }
});
var upload = multer({storage:storage,size:10225});
function checkLogin(req, res, next) {
  if(!req.session.user){
    req.flash('error','未登录！');
    res.redirect('/login');
  }
  next();
}
function checkNotLogin(req, res, next) {
  if(req.session.user){
    req.flash('error','已登录！');
    res.redirect('back');
  }
  next();
}
module.exports = router;
//首页
router.get('/', function(req, res) {
  var page = parseInt(req.query.p)||1;
  Post.getFifteen(null,page, function (err, posts,total) {
    if (err) {
      posts = [];
    }
    res.render('index',{
        user:req.session.user,
        success:req.flash('success').toString(),
        error:req.flash('error').toString(),
        posts:posts,
        img:"logo.png",
        page:page,
        isFirstPage:(page - 1) == 0,
        isLastPage:(page - 1)*15 + posts.length == total,
        total:total
    });
  });
});
//注册页面
router.get('/reg',checkNotLogin,function (req, res) {
  res.render('reg',{
    user:req.session.user,
    success:req.flash('success').toString(),
    error:req.flash('error').toString()
  })
})
router.post('/reg',function (req, res) {
  var name = req.body.name;
  var password = req.body.password;
  var password_re = req.body['password-repeat'];
  if(password_re != password){
    req.flash('error','两次输入密码不相同');
    return res.redirect('/reg');
  }
  var md5 = crypto.createHash('md5');
  var password = md5.update(req.body.password).digest('hex');

  var newUser = new User({
    name:name,
    password:password,
    email:req.body.email,
    message:req.body.message
  });
  User.get(newUser.name,function (err, user) {
    if(err){
      req.flash('error',err);
      return res.redirect('/');
    }
    if(user){
      req.flash('error','用户名已经存在 请更换')
      return res.redirect('/reg');
    }
    //如果不存在则新添加用户
    newUser.save(function (err, user) {
      if(err){
        req.flash('error',err);
        return res.redirect('/reg');
      }
      //用户信息存入session
      req.session.user = newUser;
      req.flash('success','注册成功');
      res.redirect('/login');
    })
  })
})
//登录操作
router.get('/login',checkNotLogin);
router.get('/login',function (req, res) {
  res.render('login',{
    user:req.session.user,
    success:req.flash('success').toString(),
    error:req.flash('error').toString()

  })
})
router.post('/login',function (req, res) {
  var md5 = crypto.createHash('md5');
  var password = md5.update(req.body.password).digest('hex');
  User.get(req.body.name,function (err, user) {
    if(!user){
      req.flash('error','用户名不存在');
      return res.redirect('/login');
    }
    if(user.password != password){
      req.flash('error','密码错误');
      return res.redirect('/login');
    }
    //匹配后存入用户信息session
    req.session.user = user;
    req.flash('success','登录成功');
    res.redirect('/');
  })
})
//退出登录
router.get('/logout',checkLogin);
router.get('/logout',function (req, res) {
  req.session.user = null;
  req.flash('success','退出成功');
  res.redirect('/');
})
//发表
router.get('/post',checkLogin);
router.get('/post',function (req, res) {
    res.render('post',{
      title:'发表',
      user:req.session.user,
      success:req.flash('success').toString(),
      error:req.flash('error').toString()
    })
  })
router.post('/post',function (req, res) {
  // console.log(req.body)
  var currentUser = req.session.user;
  var tags = [req.body.tag1, req.body.tag2, req.body.tag3];
  if(req.body.title == ''||req.body.post == ''){
    req.flash('error','内容不能为空');
    return res.redirect('/post');
  }
  var post = new Post(currentUser.name,req.body.title,tags,req.body.post);
  post.save(function (err) {
    if(err){
      req.flash('error','发表失败');
      return res.redirect('/post')
    }
    req.flash('success','发布成功!');
    return res.redirect('/');
  })
});
//上传文件
router.get('/upload',checkLogin);
router.get('/upload',function(req, res) {
  res.render('upload',{
    title:'文件上传',
    user:req.session.user,
    success:req.flash('success').toString(),
    error:req.flash('error').toString()
  })
});
//上传的行为
router.post('/upload',upload.array('field2',5),function(req,res){
  req.flash('success','文件保存成功');
  res.redirect('/upload');
});
//存档的路由
router.get('/archive', function (req, res) {
    Post.getArchive(function (err, posts) {
        if (err) {
            req.flash('error', err);
            return res.redirect('/');
        }
        res.render('archive', {
            title: '存档',
            posts: posts,
            user: req.session.user,
            success: req.flash('success').toString(),
            error: req.flash('error').toString()
        });
    });
});
//添加标签路由
router.get('/tags', function (req, res) {
    Post.getTags(function (err, posts) {
        if (err) {
            req.flash('error', err);
            return res.redirect('/');
        }
        res.render('tags', {
            title: '标签',
            posts: posts,
            user: req.session.user,
            success: req.flash('success').toString(),
            error: req.flash('error').toString()
        });
    });
});
//文章标签
router.get('/tags/:tag', function (req, res) {
    Post.getTag(req.params.tag, function (err, posts) {
        if (err) {
            req.flash('error',err);
            return res.redirect('/');
        }
        res.render('tag', {
            title: 'TAG:' + req.params.tag,
            posts: posts,
            user: req.session.user,
            success: req.flash('success').toString(),
            error: req.flash('error').toString()
        });
    });
});
//索引路由
router.get('/search', function (req, res) {
    Post.search(req.query.keyword, function (err, posts) {
        if (err) {
            req.flash('error', err);
            return res.redirect('/');
        }
        res.render('search', {
            title: "SEARCH:" + req.query.keyword,
            posts: posts,
            user: req.session.user,
            success: req.flash('success').toString(),
            error: req.flash('error').toString()
        });
    });
});
//获取文章的路由
router.get('/u/:name',function (req, res) {
  var page = parseInt(req.query.p) || 1;
  User.get(req.params.name,function (err, user) {
    if(err){
      req.flash('error',err);
      res.redirect('/');
    }
    if(!user){
      req.flash('error','用户不存在!');
      return res.redirect('/');
    }
    //查询并返回所有的文章
    Post.getFifteen(user.name,page,function (err, posts,total) {
      if(err){
        req.flash('error',err);
        return res.redirect('/');
      }
      res.render('user',{
        user:req.session.user,
        posts:posts,
        page: page,
        isFirstPage: (page - 1) == 0,
        isLastPage: (page - 1) * 10 + posts.length == total,
        success:req.flash('success').toString(),
        error:req.flash('error').toString(),
          total:total
      })
    })
  })
})

//文章页面的路由
router.get('/u/:name/:minute/:title',function (req, res) {
  // console.log(minute);
  Post.getOne(req.params.name,req.params.minute,req.params.title,function (err, post) {
    console.log(post);
    if(err){
      req.flash('error',err);
      return res.redirect('/');
    }
    res.render('article',{
      title:req.params.title,
      post:post,
      user:req.session.user,
      success:req.flash('success').toString(),
      error:req.flash('error').toString()
    })
  })
})
router.post('/comment/:name/:minute/:title', function (req, res) {
    var date = new Date(),
        time = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " +
            date.getHours() + ":" + (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
    var comment = {
        name: req.body.name,
        time: time,
        content: req.body.content
    };
    var newComment = new Comment(req.params.name, req.params.minute, req.params.title, comment);
    newComment.save(function (err) {
        if (err) {
            req.flash('error', err);
            return res.redirect('back');
        }
        req.flash('success', '留言成功!');
        res.redirect('back');
    });
});
//文章编辑页面的路由
router.get('/edit/:name/:minute/:title', checkLogin);
router.get('/edit/:name/:minute/:title', function (req, res) {
  var currentUser = req.session.user;
  Post.edit(currentUser.name, req.params.minute, req.params.title, function (err, post) {
    if (err) {
      req.flash('error', err);
      return res.redirect('back');
    }
    res.render('edit', {
      post: post,
      user: req.session.user,
      success: req.flash('success').toString(),
      error: req.flash('error').toString()
    });
  });
});
//文章编辑行为
router.post('/edit/:name/:minute/:title',checkLogin);
router.post('/edit/:name/:minute/:title',function(req,res){
  Post.update(req.params.name,req.params.minute,req.params.title,
      req.body.post,function(err){
        //encodeURI是防止有中文的情况下，对中文的字符进行转义
        var url = encodeURI('/u/'+ req.params.name + '/' + req.params.minute + '/' + req.params.title);
        if(err){
          req.flash('error',err);
          return res.redirect(url);
        }
        req.flash('success','编辑成功');
        return res.redirect(url);
      })
})
router.get('/remove/:name/:minute/:title', checkLogin);
router.get('/remove/:name/:minute/:title', function (req, res) {
  var currentUser = req.session.user;
  Post.remove(currentUser.name, req.params.minute, req.params.title, function (err) {
    if (err) {
      req.flash('error', err);
      return res.redirect('back');
    }
    req.flash('success', '删除成功!');
    res.redirect('/');
  });
});